<template>
  <!-- 输入框封装 -->
  <input
    :type="type"
    class="hminput"
    @input="hm"
    :class="{ seres: flag, error: !flag }"
    @blur="handleBlur"
  />
</template>

<script>
export default {
  props: {
    rules: {
      type: RegExp,
    },
    type: {
      type: String,
    },
    msg: {
      type: String,
    },
  },
  data() {
    return {
      flag: true,
    };
  },
  methods: {
    hm(e) {
      let v = e.target.value;
      // 根据用户传递的规则进行数据验证
      if (this.rules) {
        // 说明传递了验证规则
        // 进行验证
        // test是正则的验证方法，返回bool值
        if (this.rules.test(v)) {
          this.flag = true;
        } else {
          this.flag = false;
        }
      }
      this.$emit("input", v);
    },
    handleBlur(e) {
      let value = event.target.value;
      if (this.rules && !this.rules.test(value)) {
        this.$toast.fail({
          message: this.msg,
          duration: 3000,
          position: "top",
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.hminput {
  display: block;
  width: 318 * 100vw/360;
  height: 40px;
  outline: none;
  border: none;
  border-bottom: 2px solid #ccc;
  line-height: 40px;
  font-size: 20px;
  background-color: #eaeaea;
  color: #fff;
}
.seres {
  color: #07e249;
  border-bottom: 2px solid #07e249;
}
.error {
  color: rgb(226, 51, 7);
  border-bottom: 2px solid rgb(226, 51, 7);
}
</style>

